package JUC.CompletableFuture;

import lombok.Getter;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author CKC
 * @CreateTime 2022/6/7 14:21
 * <p>
 * 23集
 */
public class CompletableFutureMallDemo {
    static List<NetMall> list = Arrays.asList(
            new NetMall("taobao"),
            new NetMall("pingduoduo"),
            new NetMall("jindong"),
            new NetMall("kanyidao")
    );


    public static void main(String[] args) {

        long start = System.currentTimeMillis();
        getPrice(list, "mysql").forEach(System.out::println);
        System.out.println("总花费了:" + (System.currentTimeMillis() - start) + "毫秒");

        System.out.println("----------------------");
        long start2 = System.currentTimeMillis();
        getPriceByCompletableFuture(list, "mysql").forEach(System.out::println);
        System.out.println("总花费了:" + (System.currentTimeMillis() - start2) + "毫秒");
    }

    public static List<String> getPrice(List<NetMall> list, String productName) {
        return list
                .stream()
                .map(netMall ->
                        String.format(productName + " in %s price is %.2f",
                                netMall.getNetMallName(),
                                netMall.calcPrice(productName)))
                .collect(Collectors.toList());
    }

    public static List<String> getPriceByCompletableFuture(List<NetMall> list, String productName) {
        return list.stream()
                .map(netMall ->
                        CompletableFuture.supplyAsync(
                                () -> String.format(productName + " in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName))
                        )
                ).collect(Collectors.toList())
                .stream().map(s -> s.join()).collect(Collectors.toList());
    }


}

class NetMall {
    @Getter
    private String netMallName;

    public NetMall(String netMallName) {
        this.netMallName = netMallName;
    }

    public Double calcPrice(String productName) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}
